package com.vii.streamline.test.webserver;

import com.vii.streamline.services.error.StreamLineException;
import com.vii.streamline.structures.collections.InnerList;
import com.vii.streamline.structures.collections.InnerMap;
import com.vii.streamline.web.HttpServices;
import com.vii.streamline.webserver.WebServer;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;


public class WebTester {

    @BeforeClass
    public static void initServer() throws IOException {
        WebServer.initServer();
        WebServer.startServer();
    }


    @Test
    public void testGet() throws InterruptedException {
        WebServer.addHttpService( "/test", "/helloka", new HttpServlet() {
                @Override
                protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                    System.out.println( this.getInitParameter("enabledForExtensions") );
                    System.out.println( req.getParameter("kerdes") );
                    PrintWriter pw = resp.getWriter();
                    pw.write("Hello!!!");
                    pw.close();
                }
        }, new InnerMap<String, String>( new InnerList<String>("enabledForExtensions"), new InnerList<String>("true")) );
        CountDownLatch latch = new CountDownLatch( 1 );
        latch.await( 2000, TimeUnit.MILLISECONDS );

        try {
            HashMap map = new HashMap<String, Object>();
            map.put( "kerdes", "teszt" );
            HttpServices.sendGetMessage(
                    "http", "localhost", WebServer.PORT, "/test/helloka",
                    map
            );
        } catch (StreamLineException e) {
            e.printStackTrace();
        }

        CountDownLatch latch2 = new CountDownLatch( 1 );
        latch2.await( 2000, TimeUnit.MILLISECONDS );
    }

    @AfterClass
    public static void stopServer() {
        WebServer.stopServer();
    }

}
